package top.songxs.gmall.common.exception;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.songxs.gmall.common.execption.GmallException;
import top.songxs.gmall.common.result.Result;
import top.songxs.gmall.common.result.ResultCodeEnum;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

// com.atguigu.gmall.common.exception
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义的异常处理器
     * @param e
     * @return
     */
    @ExceptionHandler(value = GmallException.class)
    public Result gmallExceptionHandler(GmallException e) {
        e.printStackTrace();
        return Result.build(null , e.getResultCodeEnum()) ;
    }

    @ExceptionHandler(value = Exception.class)
    public Result systemExceptionHandler(Exception e) {
        e.printStackTrace();
        return Result.build(null , ResultCodeEnum.SYSTEM_ERROR) ;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        e.printStackTrace();

        Map<String , String> hashMap = new HashMap<>() ;
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for(FieldError fieldError : fieldErrors) {
            String fieldName = fieldError.getField();
            String defaultMessage = fieldError.getDefaultMessage();
            String fieldValue = hashMap.get(fieldName);
            if(StringUtils.isEmpty(fieldValue)) {           // 没有值
                hashMap.put(fieldName , defaultMessage) ;
            }else {
                fieldValue = fieldValue + ", " + defaultMessage ;
                hashMap.put(fieldName ,fieldValue ) ;
            }
        }
        Result result = new Result();
        result.setCode(9088);
        result.setMessage(JSON.toJSONString(hashMap));
        return result ;
    }
}